package com.yyfax.ph.personal.settings;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import com.umeng.analytics.AnalyticsConfig;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yyfax.ph.BuildConfig;
import com.yyfax.ph.R;
import com.yyfax.ph.StatIDSet;
import com.yyfax.ph.base.BaseYYFaxActivity;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.base.dialog.DialogBase;
import com.yyfax.ph.common.utils.Constants;
import com.yyfax.ph.common.utils.preferenceutils.PreferenceConstants;
import com.yyfax.ph.main.MainActivity;
import com.yyfax.ph.personal.authority.bankcard.view.activity.BindCardActivity;
import com.yyfax.ph.personal.authority.bankcard.view.activity.GetBindCardActivity;
import com.yyfax.ph.personal.authority.changepassword.ChangePasswordActivity;
import com.yyfax.ph.personal.authority.gesture.GesturesActivity;
import com.yyfax.ph.personal.authority.phonechange.ChangeOldPhoneActivity;
import com.yyfax.ph.personal.company.BindCompanyActivity;
import com.yyfax.ph.personal.company.ShowBindCompanyActivity;

/**
 * 设置界面
 * Created by zhangxian on 2017/11/1.<br>
 * Copyright 2017 www.yylending.com. All Rights Reserved.<br><br>
 */
public class SettingActivity extends BaseYYFaxActivity implements SettingPresenter.View, BankCardPresenter.View, GetCompanyPresenter.View {
	private static final String TAG = SettingActivity.class.getSimpleName();

	private static final int LOADER_ID_SETTING = 901;
	private static final int LOADER_ID_BANKCARD = 903;
	private static final int LOADER_ID_GET_COMPANY = 904;

	/**
	 * 姓名
	 */
	@BindView(R.id.name_tv)
	TextView mNameTv;

	@BindView(R.id.phone_tv)
	TextView mPhoneTv;

	@BindView(R.id.change_phone_tv)
	TextView mChangePhoneTv;

	@BindView(R.id.bank_card_manage_tv)
	TextView mBankCardManageTv;

	@BindView(R.id.version_tv)
	TextView mVersionTv;

	@BindView(R.id.bank_card_divider_view)
	View mBankCardDividerView;

	@BindView(R.id.change_phone_divider_view)
	View mChangePhoneDividerView;

	private int mUserType = YJPH.getInstance().getPreferenceManager().getUserType(0);

	private SettingPresenter mPresenter;
	private BankCardPresenter mBankCardPresenter;
	private GetCompanyPresenter mGetCompanyPresenter;

	private static final int CLICK_TIMES = 8;
	private static final int EACH_CLICK_INTERVAL = 200;
	// 需要监听CLICK_TIMES次点击事件
	private long[] mHints = new long[CLICK_TIMES];

	public static void start(Activity aty) {
		Intent intent = new Intent(aty, SettingActivity.class);
		aty.startActivity(intent);
	}

	@Override
	public int getContentViewRes() {
		return R.layout.setting_activity_layout;
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_SETTING:
				return new PresenterLoader<>(this, new SettingPresenter.Generator());
			case LOADER_ID_BANKCARD:
				return new PresenterLoader<>(this, new BankCardPresenter.Generator());
			case LOADER_ID_GET_COMPANY:
				return new PresenterLoader<>(this, new GetCompanyPresenter.Generator());
			default:
				break;
		}
		return null;
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {

			case LOADER_ID_SETTING:
				mPresenter = (SettingPresenter) data;
				mPresenter.attach(this);
				break;
			case LOADER_ID_BANKCARD:
				mBankCardPresenter = (BankCardPresenter) data;
				mBankCardPresenter.attach(this);
				break;
			case LOADER_ID_GET_COMPANY:
				mGetCompanyPresenter = (GetCompanyPresenter) data;
				mGetCompanyPresenter.attach(this);
				break;
			default:
				break;
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		getSupportLoaderManager().initLoader(LOADER_ID_SETTING, null, this);
		getSupportLoaderManager().initLoader(LOADER_ID_BANKCARD, null, this);
		getSupportLoaderManager().initLoader(LOADER_ID_GET_COMPANY, null, this);
	}

	@Override
	protected void onStop() {
		super.onStop();
		getSupportLoaderManager().destroyLoader(LOADER_ID_SETTING);
		getSupportLoaderManager().destroyLoader(LOADER_ID_BANKCARD);
		getSupportLoaderManager().destroyLoader(LOADER_ID_GET_COMPANY);
	}

	@Override
	public void initContentView() {
		setBtnRightVisible(false);
		setTitleLeftVisible(false);
		setTitleVisible(true);
		setTitle(R.string.setting);
		String name = YJPH.getInstance().getPreferenceManager().getUserName();
		mPhoneTv.setText(YJPH.getInstance().getPreferenceManager().getUserPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
		if (mUserType == Constants.TYPE_SUB_ACCOUNT) {
			mBankCardManageTv.setVisibility(View.VISIBLE);
			mBankCardDividerView.setVisibility(View.VISIBLE);
			mChangePhoneTv.setVisibility(View.VISIBLE);
			mChangePhoneDividerView.setVisibility(View.VISIBLE);
			if (!TextUtils.isEmpty(name)) {
				name = name.substring(0,1) + name.substring(1,name.length()).replaceAll("[\\s\\S\\d]", "*");

			}
		} else if (mUserType == Constants.TYPE_MOTHER_ACCOUNT) {
			mBankCardManageTv.setVisibility(View.GONE);
			mBankCardDividerView.setVisibility(View.GONE);
			mChangePhoneTv.setVisibility(View.GONE);
			mChangePhoneDividerView.setVisibility(View.GONE);

		}
		mNameTv.setText(TextUtils.isEmpty(name) ? getString(R.string.unrealname_certification) : name);
		mVersionTv.setText(getString(R.string.app_version, BuildConfig.VERSION_NAME));
	}

	@Override
	public void onBackBtnPressed() {
		super.onBackBtnPressed();
		finish();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		finish();
	}

	@Override
	public void getBankCardInfoSuccess(String name, String certId, String cardId, String bank, String bankCode) {

		if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(certId)) {
			if (!TextUtils.isEmpty(cardId) && !TextUtils.isEmpty(bank)) {
				GetBindCardActivity.start(this, cardId, name, bank, bankCode);
			} else {
				Intent intent = new Intent(this, BindCardActivity.class);
				intent.putExtra(GetBindCardActivity.NAME, name);
				intent.putExtra(GetBindCardActivity.CARD_ID, certId);
				BindCardActivity.start(this, intent);
			}
		} else {
			Intent intent = new Intent(this, BindCardActivity.class);
			intent.putExtra(GetBindCardActivity.NAME, name);
			intent.putExtra(GetBindCardActivity.CARD_ID, certId);
			BindCardActivity.start(this);
		}
	}

	@Override
	public void getCompanySuccess(String status, String company, String phone) {
		CLog.i(TAG, "status = " + status);
		if ((GetCompanyModel.STATUS_BIND.equals(status) || GetCompanyModel.STATUS_APPLYING.equals(status)) && !TextUtils.isEmpty(company)) {
			Intent intent = new Intent(this, ShowBindCompanyActivity.class);
			intent.putExtra(ShowBindCompanyActivity.COMPANY, company);
			intent.putExtra(ShowBindCompanyActivity.STATUS, status);
			intent.putExtra(ShowBindCompanyActivity.PHONE, phone);
			ShowBindCompanyActivity.start(this, intent);
		} else if (GetCompanyModel.STATUS_NOT_BIND.equals(status)) {
			BindCompanyActivity.start(this);
		} else {
			showToast(R.string.common_network_unavailable);
		}
	}


	@Override
	public void getBankCardInfoFailed(String tips) {
		showToast(tips);
	}

	@Override
	public void logoutSuccess(String tips) {
		CLog.i(TAG, "logoutSuccess");
		YJPH.getInstance().onLogoutSuccess();
		MainActivity.start(this, true);
		/***
		 * 退出登录成功后停止极光推送服务 不再接收消息
		 */
		JPushInterface.stopPush(YJPH.getInstance());
		YJPH.getInstance().getPreferenceManager().savePreference(PreferenceConstants.SP_KEY_BIND_JPUSH_FLAG, false);
		finish();
	}

	@Override
	public void logoutFailure(String tips) {
		CLog.i(TAG, "logoutFailure");
		showToast(tips);
	}

	@OnClick({R.id.change_pwd_tv, R.id.change_gesture_code_tv, R.id.change_phone_tv, R.id.bank_card_manage_tv, R.id.logout_tv, R.id.my_channel_tv, R.id.version_tv})
	public void onViewClick(View view) {
		super.onClick(view);
		switch (view.getId()) {
			case R.id.change_pwd_tv:
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_E020);
				ChangePasswordActivity.start(this);
				break;
			case R.id.change_gesture_code_tv:
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_E022);
				GesturesActivity.start(this);
				break;
			case R.id.change_phone_tv:
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_E023);
				ChangeOldPhoneActivity.start(this);
				break;
			case R.id.bank_card_manage_tv:
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_E026);
				if (YJPH.getInstance().getPreferenceManager().isLoginSuccess()) {
					mBankCardPresenter.getBindBankCardInfo();//检查绑定的银行卡信息再决定跳转的目标Activity
				}
				break;
			case R.id.my_channel_tv:
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_E032);
				if (mUserType == Constants.TYPE_MOTHER_ACCOUNT) {
					Intent intent = new Intent(this, ShowBindCompanyActivity.class);
					intent.putExtra(ShowBindCompanyActivity.COMPANY, YJPH.getInstance().getPreferenceManager().getUserName());
					intent.putExtra(ShowBindCompanyActivity.STATUS, "");
					intent.putExtra(ShowBindCompanyActivity.PHONE, YJPH.getInstance().getPreferenceManager().getUserPhone());
					ShowBindCompanyActivity.start(this, intent);
				} else {
					mGetCompanyPresenter.getBindCompany();
				}
				break;
			case R.id.logout_tv:
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_E036);
				//弹出对话框,确认注销号码
				showTipsDialog(getString(R.string.confirm_logout), R.string.cancel, R.string
						.confirm, new DialogBase.BottomTwoClickListener() {
					@Override
					public void onCancelClick(DialogBase dialog) {
						dialog.dismiss();
					}

					@Override
					public void onConfirmClick(DialogBase dialog) {
						StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_E037);
						mPresenter.logout();
					}
				});
				break;
			case R.id.version_tv:
				resolveBackDoor();
				break;
				default:
					break;
		}
	}

	private void resolveBackDoor() {
		// 将mHints数组内的所有元素左移一个位置
		System.arraycopy(mHints, 1, mHints, 0, mHints.length - 1);
		// 获得当前系统已经启动的时间
		mHints[mHints.length - 1] = SystemClock.uptimeMillis();
		if (SystemClock.uptimeMillis() - mHints[0] <= CLICK_TIMES * EACH_CLICK_INTERVAL) {
			showToast(AnalyticsConfig.getChannel(this) + "_" + BuildConfig.VERSION_NAME + "_" + BuildConfig.VERSION_CODE + "_" + BuildConfig.BUILD_TYPE);
		}
	}
}